//index.js
const app = getApp()
const db = wx.cloud.database()
const db_shipment = db.collection('shipment')

function js_date_time(unixtime) {
  var date = new Date(unixtime);
  var y = date.getFullYear();
  var m = date.getMonth() + 1;
  m = m < 10 ? ('0' + m) : m;
  var d = date.getDate();
  d = d < 10 ? ('0' + d) : d;
  var h = date.getHours();
  h = h < 10 ? ('0' + h) : h;
  var minute = date.getMinutes();
  var second = date.getSeconds();
  minute = minute < 10 ? ('0' + minute) : minute;
  second = second < 10 ? ('0' + second) : second;
  // return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;//年月日时分秒
  return y + '-' + m + '-' + d + ' ' + h + ':' + minute;

}
let plugin = requirePlugin("WechatSI")
let manager = plugin.getRecordRecognitionManager()
manager.onRecognize = function (res) {
  console.log("current result", res.result)
}
manager.onStop = function (res) {
  console.log("record file path", res.tempFilePath)
  console.log("result", res.result)
}
manager.onStart = function (res) {
  console.log("成功开始录音识别", res)
}
manager.onError = function (res) {
  console.error("error msg", res.msg)
}
// 转译
// plugin.translate({
//   lfrom: "en_US",
//   lto: "zh_CN",
//   content: "hello, this is the first time to test？",
//   success: function (res) {
//     if (res.retcode == 0) {
//       console.log("result", res.result)
//     } else {
//       console.warn("翻译失败", res)
//     }
//   },
//   fail: function (res) {
//     console.log("网络失败", res)
//   }
// })
// 文字转语音
// plugin.textToSpeech({
//   lang: "zh_CN",
//   tts: true,
//   content: "一个常见的需求",
//   success: function (res) {
//     console.log("succ tts", res.filename)
//   },
//   fail: function (res) {
//     console.log("fail tts", res)
//   }
// })
Page({
  data: {
    avatarUrl: './user-unlogin.png',
    userInfo: {},
    logged: false,
    takeSession: false,
    requestResult: '',
    filename: '',
    onlyFromCameraState: false
  },

  onLoad: function () {
    if (!wx.cloud) {
      wx.showToast({
        title: '初始化失败',
      })
      return
    }

    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              console.log(res)
              this.setData({
                avatarUrl: res.userInfo.avatarUrl,
                userInfo: res.userInfo
              })
            }
          })
        }
      }
    })
  },

  onGetUserInfo: function (e) {
    if (!this.data.logged && e.detail.userInfo) {
      this.setData({
        logged: true,
        avatarUrl: e.detail.userInfo.avatarUrl,
        userInfo: e.detail.userInfo
      })
    }
  },

  onGetOpenid: function () {
    // 调用云函数
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        console.log(res)
        console.log('[云函数] [login] user openid: ', res.result.openid)
        app.globalData.openid = res.result.openid
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
      }
    })
  },
  shipment: function () {
    let that = this
    wx.showLoading({
      title: '识别中，请稍后',
      mask: true
    })
    wx.scanCode({
      onlyFromCamera: that.onlyFromCameraState, //仅仅相机
      success: (res) => {
        console.log(res)
        db_shipment.where({
          rawData: res.rawData
        }).get({
          success: function (whereRes) {
            console.log(whereRes.data)
            if (whereRes.data.length > 0) {
              wx.showToast({
                title: `此商品已在${whereRes.data[0].time}添加`,
                icon: 'none',
                duration: 3000
              })
              that.textToSpeech(`此商品已在${whereRes.data[0].time}添加`)
            } else {
              res.time = js_date_time(new Date().getTime());
              db_shipment.add({
                data: res,
                success: function (ress) {
                  console.log(ress)
                  wx.showToast({
                    title: '添加成功',
                    icon: 'none',
                    duration: 3000
                  })
                  that.textToSpeech(`添加成功`)

                }
              })
            }
          }
        });


      },
      //错误返回
      fail: (res) => {
        console.log(res)
        wx.showToast({
          title: '已取消',
          icon: 'none',
          duration: 3000
        })
      },
      // complete: function (res) {
      //   wx.showToast({
      //     title: 'complete',
      //     icon: 'none',
      //     duration: 1000
      //   })
      // },
    })

  },
  salesReturn: function () {
    let that = this;
    wx.showLoading({
      title: '识别中，请稍后',
      mask: true
    })
    wx.scanCode({
      onlyFromCamera: that.onlyFromCameraState, //仅仅相机
      success: (res) => {
        console.log(res)
        db_shipment.where({
          rawData: res.rawData
        }).get({
          success: function (whereRes) {
            console.log(whereRes.data)
            if (whereRes.data.length > 0) {
              wx.showToast({
                title: `此商品在${whereRes.data[0].time}添加`,
                icon: 'none',
                duration: 3000
              })
              that.textToSpeech(`此商品在${whereRes.data[0].time}添加`)
            } else {
              wx.showToast({
                title: `此商品不是本店出售`,
                icon: 'none',
                duration: 3000
              })
              that.textToSpeech(`此商品不是本店出售`)
            }
          }
        })
      },
      //错误返回
      fail: (res) => {
        console.log(res)
        wx.showToast({
          title: '已取消',
          icon: 'none',
          duration: 3000
        })
      },
      // complete: function (res) {
      //   wx.showToast({
      //     title: 'complete',
      //     icon: 'none',
      //     duration: 1000
      //   })
      // },
    })


  },
  textToSpeech: function (content) {
    let that = this;
    wx.hideLoading()
    plugin.textToSpeech({
      lang: "zh_CN",
      tts: true,
      content: content,
      success: function (res) {
        console.log("succ tts", res.filename)
        that.setData({
          filename: res.filename
        })
      },
      fail: function (res) {
        console.log("fail tts", res)
      }
    })
  }
})